<?php

namespace App\Admin\Actions\Category;

use App\Library\Logic\OperateLogLogic;
use App\Models\ShopCategoryModel;
use Encore\Admin\Actions\Response;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;

class AddThirdCategoryAction extends RowAction
{
    public $name = '新增三级分类';

    public function handle(ShopCategoryModel $model, Request $request): Response
    {
        if (is_null($model) || $model->status_delete) return $this->response()->error(__('errorCode.433'))->refresh();

        $category = ShopCategoryModel::insertForModel([
            'categoryStatus' => $request->status,
            'categoryName' => $request->categoryName,
            'sort' => $request->sort,
            'categoryTopParentId' => $model->category_top_parent_id,
            'categoryParentId' => $model->category_id,
            'categoryLevel' => $model->category_top_parent_id . ',' . $model->category_id,
        ]);

        OperateLogLogic::add(Admin::user()->user_id, 'admin.category.add', [
            'categoryTopParentId' => $model->category_top_parent_id,
            'categoryParentId' => $model->category_id,
            'categoryLevel' => $model->category_top_parent_id . ',' . $model->category_id,
        ]);

        return $this->response()->success('操作成功')->refresh();
    }

    public function form(): void
    {
        $this->text('categoryName', __('category.category_name'))->rules('required|string|max:255');
        $this->select('status', __('category.status'))->default(2)->options(__('category.statusArr'));
        $this->text('sort', __('category.sort'))->default(0)->rules('nullable|integer|min:0');
    }

    public function html(): string
    {
        return "<a class='report-posts btn btn-sm btn-danger'><i class='fa fa-info-circle'></i>确认</a>";
    }
}
